import Axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
} from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import config from '@/config'

let service: AxiosInstance = Axios.create({
  baseURL: config.API_URL,
  timeout: 5000,
});

service.interceptors.request.use(
  (requestConfig: AxiosRequestConfig): AxiosRequestConfig => {
    NProgress.start();
    // JWT鉴权
    let token: string | null = sessionStorage.getItem("token");
    if (token) {
      requestConfig.headers[config.TOKEN_NAME] = config.TOKEN_PREFIX + token;
    }

    return requestConfig;
  },
  (err: AxiosError) => {
    NProgress.done();
    return err
  }
);

service.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    NProgress.done();
    return response;
  },
  (err: AxiosError) => {
    NProgress.done();
    return err;
  }
);

const request = (url: string, data: any={}, method: string='GET') => {
  return new Promise((resolve, reject) => {
    let p: any

    if (method === 'GET') {
      p = service.get(url, {params: data})
    } else {
      p = service.post(url, data)
    }

    p
    .then((data: any) => {
      resolve(data)
    })
    .catch((reason: any) => {
      reject(reason)
    })
  })
}

export default request;
